package com.maqconfig.exception;

import common.MQR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public MQR customExceptionHandler(HttpServletRequest request, HandlerMethod handlerMethod, Exception e){
        log.error(String.format("访问 %s --> %s 出错！",request.getRequestURI(),handlerMethod.toString()),e);
        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            BindingResult bindingResult = ex.getBindingResult();
            StringBuilder errMsg = new StringBuilder(bindingResult.getFieldErrors().size() * 16);
            for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
                if (i > 0) {
                    errMsg.append(",");
                }
                FieldError error = bindingResult.getFieldErrors().get(i);
                errMsg.append(error.getDefaultMessage());
            }
            return MQR.ERROR(errMsg.toString());
        } else {
            return MQR.ERROR(e.getMessage()==null?"空指针异常":e.getMessage());
        }
    }
}
